<template>
  <div class="h-full box-border overflow-auto bg-gray-100">
    <div class="rounded bg-white shadow m-3 p-3">
      <el-upload
        class="border border-dashed border-gray-300 rounded hover:border-blue-500 transition-colors"
        action="###"
        :show-file-list="false"
        :auto-upload="true"
        :before-upload="(e:any)=>beforeUpload(e)"
        :limit="1"
        :http-request="(e:any)=>httpRequest(e)"
      >
        <img
          v-if="imageUrl"
          :src="imageUrl"
          class="max-h-full max-w-full m-auto block"
        />
        <div v-else class="absolute top-1/2 left-1/2 -mt-4 -ml-4 w-8 h-8">
          <Plus class="text-gray-400" />
        </div>
      </el-upload>
      <div class="w-[200px] h-[200px] inline-block overflow-auto">
        <img ref="imgRef" :src="imageUrl" />
      </div>
      <div class="w-[200px] h-[200px] inline-block overflow-auto">
        <canvas ref="canvasRef"></canvas>
      </div>
      <div class="mt-3">
        <el-button type="primary" @click="() => onClickDraw()">
          画图
        </el-button>
        <el-button type="primary" @click="() => onClickAnalyze()">
          解析
        </el-button>
      </div>
    </div>
    <div class="rounded bg-white shadow m-3 p-3">
      <el-input
        type="textarea"
        :rows="100"
        placeholder="xml输出结果"
        v-model="textareaContent"
        class="w-full"
      ></el-input>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { ref } from "vue";
const imgRef = ref(null);
const canvasRef = ref(null);
const imageUrl = ref("");
const textareaContent = ref("");
const httpRequest = (e: any) => {
  /**
   * el upload返回的file
   */
  const imageFile: File | undefined = e["file"];
  /**
   * 文件读取工具
   */
  let fileReader = new FileReader();
  /**
   * 图片对象
   */
  let image = new Image();
  // 当 el upload 返回的file为空时
  if (!imageFile) {
    ElMessage.error("读取图片出错：el upload返回的图片为空");
    return;
  }
  fileReader.readAsDataURL(imageFile);
  fileReader.onload = (e) => {
    console.log("onload: ", e);
    if (!e.target) {
      return;
    }
    if (!e.target.result) {
      return;
    }
    imageUrl.value = e.target.result.toString();
  };
};
const beforeUpload = (e: any) => {
  // console.log(e);
};
const getImageStyle = () => {
  if (!imgRef.value) {
    ElMessage.error("vue3 img ref为空");
    return;
  }
  const imgHtml = imgRef.value as HTMLImageElement;
  const resultStyle = {
    width: imgHtml.offsetWidth,
    height: imgHtml.offsetHeight,
    widthString: imgHtml.offsetWidth + "px",
    heightString: imgHtml.offsetHeight + "px",
  };
  return resultStyle;
};
/**
 * 把图片画到canvas上
 */
const onClickDraw = () => {
  if (!canvasRef.value) {
    ElMessage.error("vue3 canvase ref为空");
    return;
  }
  let canvasElement = canvasRef.value as HTMLCanvasElement;
  let context2D = canvasElement.getContext("2d");
  if (!context2D) {
    ElMessage.error("context 2d 为空");
    return;
  }
  if (!imgRef.value) {
    ElMessage.error("vue3 img ref为空");
    return;
  }
  let image = new Image();

  image.src = imageUrl.value;
  image.onload = () => {
    const style = getImageStyle();
    if (!context2D) {
      ElMessage.error("context 2D 为空");
      return;
    }
    if (!style) {
      ElMessage.error("style 为空");
      return;
    }
    console.log(style, image.src);

    canvasElement.width = style.width;
    canvasElement.height = style.height;
    // canvasElement.style.width = style.widthString;
    // canvasElement.style.height = style.heightString;
    context2D.drawImage(image, 0, 0);
  };
};
const getRgbArray = (data: Uint8ClampedArray) => {
  let rgbArray: { r: number; g: number; b: number }[] = [];
  for (let index = 0; index < data.length; index += 4) {
    const rgb = {
      r: data[index],
      g: data[index + 1],
      b: data[index + 2],
    };
    rgbArray.push(rgb);
  }
  return rgbArray;
};
const gethex = (rN: number, gN: number, bN: number) => {
  //   console.log(rN, gN, bN);

  let r = rN.toString(16);
  let g = gN.toString(16);
  let b = bN.toString(16);

  // 补0
  r.length == 1 ? (r = "0" + r) : "";
  g.length == 1 ? (g = "0" + g) : "";
  b.length == 1 ? (b = "0" + b) : "";

  var hex = r + g + b;

  // 简化处理,如 FFEEDD 可以写为 FED
  //   if (
  //     r.slice(0, 1) == r.slice(1, 1) &&
  //     g.slice(0, 1) == g.slice(1, 1) &&
  //     b.slice(0, 1) == b.slice(1, 1)
  //   ) {
  //     hex = r.slice(0, 1) + g.slice(0, 1) + b.slice(0, 1);
  //   }

  return hex;
};
const getHexArray = (
  rgbArray: {
    r: number;
    g: number;
    b: number;
  }[] = []
) => {
  return rgbArray.map((item) => {
    return gethex(item.r, item.g, item.b);
  });
};
const onClickAnalyze = () => {
  //   console.log("here: ", imageUrl.value);
  //   console.log(canvasRef.value, document.getElementById("canvas"));
  if (!canvasRef.value) {
    ElMessage.error("vue3 canvase ref为空");
    return;
  }
  const canvasElement = canvasRef.value as HTMLCanvasElement;
  const context2D = canvasElement.getContext("2d");
  if (!context2D) {
    ElMessage.error("context 2d 为空");
    return;
  }
  const style = getImageStyle();
  if (!style) {
    ElMessage.error("style 为空");
    return;
  }
  const data = context2D.getImageData(0, 0, style.width, style.height).data;
  const resultRGB = getRgbArray(data).map((item) => {
    return {
      r: Math.floor(item.r / 2),
      g: Math.floor(item.g / 2),
      b: Math.floor(item.b / 2),
    };
  });
  const result = getHexArray(resultRGB);
  //   console.log("here: ", resultRGB, result);
  const bgItemArray = result
    .map((item, index) => {
      if (item === "7f7f7f") {
        return null;
      }
      const x = (index + 1) % style.width;
      const y = Math.floor((index + 1) / style.width);
      const bgItem = `<bg x="${x}" y="${y}" w="1" h="1" m="3" c="#${item}" />`;
      return bgItem;
    })
    .filter((item) => !!item);
  let text = "";
  bgItemArray.forEach((item) => {
    text = text + item + "\n";
  });
  textareaContent.value = text;

  //   console.log(
  //     "context ",
  //     context2D.getImageData(0, 0, style.width, style.height)
  //   );
};
</script>
